import 'package:flutter_ohos_sqflite_demo/todo.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class DatabaseHelper {
  static final DatabaseHelper _instance = DatabaseHelper._internal();
  factory DatabaseHelper() => _instance;
  DatabaseHelper._internal();

  static Database? _database;
  final String _tableName = "todos";
  final String _columnId = "id";
  final String _columnTitle = "title";
  final String _columnDesc = "description";
  final String _columnDate = "date";
  final String _columnIsDone = "isDone";

  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDB();
    return _database!;
  }

  Future<Database> _initDB() async {
    final path = join(await getDatabasesPath(), 'todo_database.db');
    return openDatabase(
      path,
      version: 1,
      onCreate: (db, version) async {
        await db.execute(
          "CREATE TABLE $_tableName("
          "$_columnId INTEGER PRIMARY KEY AUTOINCREMENT, "
          "$_columnTitle TEXT NOT NULL, "
          "$_columnDesc TEXT, "
          "$_columnDate TEXT NOT NULL, "
          "$_columnIsDone INTEGER DEFAULT 0)"
        );
      }
    );
  }

  // 插入新Todo
  Future<int> insertTodo(Todo todo) async {
    final db = await database;
    return await db.insert(_tableName, todo.toMap());
  }

  // 获取所有Todo
  Future<List<Todo>> getTodos() async {
    final db = await database;
    final List<Map<String, dynamic>> maps = await db.query(_tableName);
    return List.generate(maps.length, (i) => Todo.fromMap(maps[i]));
  }

  // 更新Todo
  Future<int> updateTodo(Todo todo) async {
    final db = await database;
    return await db.update(
      _tableName,
      todo.toMap(),
      where: "$_columnId = ?",
      whereArgs: [todo.id],
    );
  }

  // 删除Todo
  Future<int> deleteTodo(int id) async {
    final db = await database;
    return await db.delete(
      _tableName,
      where: "$_columnId = ?",
      whereArgs: [id],
    );
  }
}